﻿using System.ComponentModel;

namespace Service.Framework.Utils.Extension
{
    public static class EnumExtension
    {
        public static Int32 GetInt32(this Enum @enum)
        {
            return Convert.ToInt32(@enum);
        }

        public static Int16 GetInt16(this Enum @enum)
        {
            return Convert.ToInt16(@enum);
        }

        public static Byte Byte(this Enum @enum)
        {
            return Convert.ToByte(@enum);
        }
        /// <summary>
        /// 枚举转化为注释，需要在枚举上加上此<see cref="System.ComponentModel.DescriptionAttribute"/>特性
        /// </summary>
        /// <param name="val">枚举值</param>
        /// <param name="type">枚举类型</param>
        /// <returns></returns>
        public static String ToDescription(this Enum val, Type type = null)
        {
            if (type == null)
            {
                type = val.GetType();
            }
            var memberInfo = type.GetMember(val.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes == null || attributes.Length != 1)
            {
                return val.ToString();
            }
            return (attributes.Single() as DescriptionAttribute).Description;
        }




    }
}
